﻿using JQ.ServiceManager.Base;
using JQ.ServiceManager.Base.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace JQ.ServiceManager.views
{
    /// <summary>
    /// UCServiceView.xaml 的交互逻辑
    /// </summary>
    public partial class UCServiceView : UserControl
    {
        private ObservableCollection<ServiceManagementObject> myVar;

        public ObservableCollection<ServiceManagementObject> RawData
        {
            get { return myVar; }
            set { myVar = value; }
        }


        private ObservableCollection<ServiceManagementObject> servManageObjs;

        public ObservableCollection<ServiceManagementObject> ServManageObjs
        {
            get { return servManageObjs; }
            set { servManageObjs = value; }
        }

        private ServiceManagementObject selectedServObj;

        public ServiceManagementObject SelectedServObj
        {
            get { return selectedServObj; }
            set { selectedServObj = value; }
        }

        public Action<ServiceManagementObject> OnServiceSelected { get; set; }


        public UCServiceView()
        {
            InitializeComponent();
            this.DataContext = this;
            Load();
        }

        private void Load()
        {
            ServManageObjs = new ObservableCollection<ServiceManagementObject>();
            RawData = new ObservableCollection<ServiceManagementObject>();
            var serviceManageObjs = ServiceOperation.GetServiceInfoFromWMI("");
            foreach(var servObj in serviceManageObjs)
            {
                ServManageObjs.Add(servObj);
                RawData.Add(servObj);
            }
        }

        public void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        private void FilterKey_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
            {
                string key = FilterKey.Text;
                ServManageObjs.Clear();
                var selectedServObjs = RawData.Where(it => it.Name.Contains(key) || it.DisplayName.Contains(key)).ToList();
                selectedServObjs.ForEach(it => ServManageObjs.Add(it));
            }
        }

        private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if(SelectedServObj != null)
            {
                OnServiceSelected?.Invoke(SelectedServObj);
            }
        }
    }
}
